<template>  
<div class="register">
  <div class="box">
    <h2>用户注册</h2>
    
  <el-form :model="registerForm" :rules="rules" ref="registerForm" label-width="80px">
  <el-form-item label="手机号" prop="phone" >
    <el-input type="text" v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
  </el-form-item>
  <el-form-item label="姓名" prop="name">
    <el-input type="text" v-model="registerForm.name" placeholder="请输入姓名"></el-input>
  </el-form-item>
  <el-form-item label="年龄" prop="age">
    <el-input type="text" v-model="registerForm.age" placeholder="请输入年龄"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="rawPassword">
    <el-input type="password" v-model="registerForm.rawPassword" placeholder="请输入密码"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button @click="submitForm('registerForm')">立即创建</el-button>
  </el-form-item>
  
</el-form>
</div>
</div>
</template>  

<script>  

import JSEncrypt from 'jsencrypt';  
  export default {  
    data() {  
      return {  
        adminname: '',  
        password: '',
        title:'注册',
        registerForm:{
            phone:"",
            name:'',
            age:'',
            rawPassword: '',  
            // encryptedPassword: '',  
        },
        rules: {  
        phone: [  
          { required: true, message: '请输入手机号', trigger: 'blur' },  
          { min: 11, max: 11, message: '手机号长度必须为11位', trigger: 'blur' },  
        ],  
        name: [  
          { required: true, message: '请输入姓名', trigger: 'blur' },  
        ],  
        age: [  
          { required: true, message: '请输入年龄', trigger: 'blur' },  
        ],  
        rawPassword: [  
          { required: true, message: '请输入密码', trigger: 'blur' },  
        ],  
      },  
      publicKey: '', // 公钥 
      }  
    }, 
    methods: {
        register() {
            const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
        });
        console.log("跳转注册页面");
        this.$axios({
            headers: { "Content-Type": "application/json;" },
            method: "post",
            url: "http://"+this.URLhost+"/api/user/register",
            data: JSON.stringify({
            userPhone: this.registerForm.phone,
            userName:this.registerForm.name,
            userAge:this.registerForm.age,
            userPassword: this.registerForm.encryptedPassword,
            }),
        })
        .then((res) => {
            console.log("456456", res.data);
            if (res.data === 0) {
            this.$router.push({
                name: "Login"
            });
            this.$message({
                message: "注册成功",
                type: "success",
            });
            }
            else {alert('用户已注册');}
            loading.close();
        });

        setTimeout(() => {
            loading.close();
        }, 5000);
        },
        
        // 未联机代码
        // submitForm(formName) {  
        // this.$refs[formName].validate((valid) => { // 表单验证  
        //   console.log("进入login")  
        //         if (valid) {    
        //           console.log("valid")  
        //             // 表单验证通过，执行跳转操作    
        //             this.$router.push('/login'); // 替换为您的Login页面的路由路径    
        //             this.$message({
        //                 message: "注册成功",
        //                 type: "success",
        //             });
        //           } else {    
        //           console.log("进入unlogin")  
        //             this.$message({  
        //                 message: '用户已注册',  
        //                 type: 'warning'  
        //             });    
        //             return false;    
        //         }    
        // });  
        // },
        //
        
        // //联机代码
        // submitForm(registerForm){
        // this.$refs[registerForm].validate((valid) => {
        //     if(valid){
        //         this.register();
        //     }
        //     else{
        //         console.log("用户已注册");  
        //     return false;  
        //     }
        // })
        // },
        // //

    async submitForm(registerForm) {  
      this.$refs[registerForm].validate(async (valid) => {  
        if (valid) {  
          try {  
            // 从后端获取公钥  
            this.publicKey = await this.getPublicKey();  
              
            // 使用公钥加密密码  
            const encryptedPassword = this.encryptPassword(this.registerForm.rawPassword);  
              
            // 将加密后的密码保存到表单中  
            this.registerForm.encryptedPassword = encryptedPassword;  
              
            // 调用注册方法  
            this.register();  
          } catch (error) {  
            console.error("加密或注册过程中发生错误:", error);  
          }  
        } else {  
          console.log("表单验证失败");  
          return false;  
        }  
      });  
    },  
    async getPublicKey() {  
      try {  
        const response = await this.$axios.get("http://"+this.URLhost+"/api/user/publicKey"); // 获取公钥的接口  
        console.log('获取到公钥为'+response.data.publicKey)
        return response.data.publicKey; // 假设后端返回的数据结构中包含公钥字段  
      } catch (error) {  
        throw new Error("无法获取公钥");  
      }  
    },  
    encryptPassword(rawPassword) {  
      if (!this.publicKey) {  
        throw new Error("公钥未定义，无法加密密码");  
      }  
      const encrypt = new JSEncrypt();  
      encrypt.setPublicKey(this.publicKey);  
      return encrypt.encrypt(rawPassword);  
    },  

        mounted() {  
                document.title = this.title; // 设置网页标签的名称  
            }
    }
}  
  </script>


  <style scoped>  
  .register {
  width: 100%;
  height: 100%;
  /*背景图片*/
  /* background-image: url("../"); */
  position: fixed;
  background-size: cover;
}

.box {  
  position: absolute;  
  display: flex; 
  flex-direction: column; 
  justify-content: center;  
  align-items: center;  
  left: 0;  
  right: 0;  
  top: 0;  
  bottom: 0;  
  width: 500px;  
  height: 450px;  
  margin: auto;  
  border: 1px solid #ccc;    
  background-color: rgba(255, 255, 255, 0.34);    
}  
  
.box h2 {  
  padding: 20px 0 20px 0;  
  font-size: 30px;  
  font-weight: 900;  
  
  line-height: 30px;  
  color: #3333aa;  
}  


.el-form .el-form-item i {  
  width: 50px;  
  color: #3333aa;  
}  
  
.el-form .el-form-item .el-input {  
  width: 250px;  
}  
  
.el-form .el-form-item .el-button {  
  background-color: #3333aa;   
  text-align: center; 
  width: 150px;
  color: #fff;    
  padding: 10px 30px;    
  border: 1px solid #fff;   
  cursor: pointer;    
  font-size: 18px;    
}  

</style>